﻿using UnityEngine;
using System.Collections;
using TinaX.XComponent;

[RequireComponent(typeof(XComponent))]
public class MonoObj2Lua : MonoBehaviour
{
	#region Middle Layer
	private XComponent xComponent;
	[SerializeField]
	protected string _luaName;
	#endregion

	private XComponent GetXComponent()
	{
		if (xComponent == null)
			xComponent = this.GetComponent<XComponent>();
		if (xComponent == null)
			Debug.LogError("Can not find xComponent:" + this.gameObject.name, this.gameObject);
		return xComponent;
	}

	XLua.LuaTable _luaIns;
	protected virtual void OnEnable()
	{
		CallLuaFunction("_OnEnable");
	}

	protected virtual void OnDisable()
	{
		CallLuaFunction("_OnDisable");
	}

	protected virtual void Awake()
	{
		_luaIns = this.OnGetLuaIns();
		if (_luaIns == null)
			return;
		_luaIns.Set("gameObject", this.gameObject);
		_luaIns.Set("xComponent", this.GetXComponent());
		CallLuaFunction("Awake");
	}

	protected virtual XLua.LuaTable OnGetLuaIns()
	{
		var luaClass = LuaMgr.luaEnv.Global.Get<XLua.LuaTable>(this.OnGetObjName());
		if (luaClass == null)
		{
			UnityEngine.Debug.LogError("不影响游戏运行：Can not find Lua Golbal Class:" + this.OnGetObjName());
			return null;
		}
		var newFunc = luaClass.Get<XLua.LuaFunction>("New");
		return newFunc.Func<MonoObj2Lua, XLua.LuaTable>(this);
	}

	protected virtual void Start()
	{
		CallLuaFunction("Start");
	}

	protected virtual void OnDestroy()
	{
		if (CallLuaFunction("OnDestroy"))
			_luaIns.Dispose();
	}

	public void Destroy()
    {
		if (!XRes.ReleaseInstance(this.gameObject))
			GameObject.Destroy(this.gameObject);
    }

	protected virtual void Update()
	{

	}

	private string OnGetObjName()
	{
		if (string.IsNullOrEmpty(_luaName))
			return this.gameObject.name;
		else
			return _luaName;
	}

	private bool CallLuaFunction(string funcName)
	{
		if (_luaIns == null)
			return false;
		_luaIns.Get<XLua.LuaFunction>(funcName).Call(_luaIns);
		return true;
	}
}
